package cn.tsoft.taobao.db;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import cn.tsoft.taobao.util.AuthorInfo;
import cn.tsoft.taobao.util.DateTimeUtil;
import cn.tsoft.taobao.util.HttpEngine;
import cn.tsoft.taobao.util.Utils;
import cn.tsoft.vo.ItemForDetail;



public class TaoBaoDataManager {
	
	
	public static List<Map<String, Object>> getOnSaleProductList() {
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		HttpEngine httpEngine = new HttpEngine();
		httpEngine.getHttpClient();
		String fields = "num_iid,title,price,valid_thru,pic_url,num";
		String method = "taobao.items.onsale.get";
		String format = "json";
		List<NameValuePair> params = httpEngine.getTopSessionUrl(method,
				fields, format, false);
		Map<String, String> signParams = new HashMap<String, String>();
		signParams.put("fields", fields);
		signParams.put("format", format);
		signParams.put("method", method);
		String sign = getSign(signParams);
		// 组装协议参数sign
		params.add(new BasicNameValuePair("sign", sign));
		String resultStr = httpEngine.doPost(AuthorInfo.TOP_URL, params);
		try {
			JSONObject  jsonObject = new JSONObject(resultStr).getJSONObject("items_onsale_get_response").getJSONObject("items");
			JSONArray array = jsonObject.getJSONArray("item");
			for(int i=0 ; i < array.length() ; i++){
				Map<String, Object> inner = new HashMap<String, Object>();
				JSONObject item = array.getJSONObject(i);
				inner.put("item_image", item.get("pic_url"));
				inner.put("title", item.getString("title"));
				inner.put("price", item.getString("price"));
				inner.put("time", item.getString("valid_thru"));
				inner.put("num", item.getString("num"));
				inner.put("productId", item.getLong("num_iid"));
				result.add(inner);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} 
		return result;
	}
	
	/**
	 * 统计交易订单数量
	 * @author wanggj
	 */
	public static Map<String, Object> getTradeOrderList() {
		HashMap<String, Object> result = new HashMap<String, Object>();
		
 		List<Map<String, Object>> mainlist = new ArrayList<Map<String,Object>>();
 		
 		List<List<Map<String, Object>>> childData = new ArrayList<List<Map<String, Object>>>();
 		
		HttpEngine httpEngine = new HttpEngine();
		httpEngine.getHttpClient();
		String fields = "status,price,title,orders.pic_path,orders.title,orders.num,orders.payment";
		String method = "taobao.trades.sold.get";
		String format = "json";
		List<NameValuePair> params = httpEngine.getTopSessionUrl(method,
				fields, format, false);
		Map<String, String> signParams = new HashMap<String, String>();
		signParams.put("fields", fields);
		signParams.put("format", format);
		signParams.put("method", method);
		String sign = getSign(signParams);
		// 组装协议参数sign
		params.add(new BasicNameValuePair("sign", sign));
		String resultStr = httpEngine.doPost(AuthorInfo.TOP_URL, params);
		try {
			JSONObject  jsonObject = new JSONObject(resultStr).getJSONObject("trades_sold_get_response").getJSONObject("trades");
			JSONArray array = jsonObject.getJSONArray("trade");
			/**
			 * 交易状态。可选值:
		    * TRADE_NO_CREATE_PAY(没有创建支付宝交易)
		    * WAIT_BUYER_PAY(等待买家付款)
		    * WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款)
		    * WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货)
		    * TRADE_BUYER_SIGNED(买家已签收,货到付款专用)
		    * TRADE_FINISHED(交易成功)
		    * TRADE_CLOSED(付款以后用户退款成功，交易自动关闭)
		    * TRADE_CLOSED_BY_TAOBAO(付款以前，卖家或买家主动关闭交易)
			 */
			int WAIT_BUYER_PAY =0;
			int	WAIT_SELLER_SEND_GOODS =0 ;
			int	WAIT_BUYER_CONFIRM_GOODS =0;
			int TRADE_FINISHED = 0;
			int TRADE_CLOSED =0;
			for(int i=0 ; i < array.length() ; i++){
				JSONObject item = array.getJSONObject(i);
				String status =  item.get("status").toString();
				
				JSONArray   orders  =  item.getJSONArray("order");
				if(!status.equals("TRADE_CLOSED") &&  !status.equals("TRADE_CLOSED_BY_TAOBAO")){
						for(int j=0;j<orders.length();j++){
							List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
							Map<String, Object> curChildMap = new HashMap<String, Object>();
							children.add(curChildMap);
							curChildMap.put("image", item.get("pic_path"));
							curChildMap.put("title", item.get("title"));
							curChildMap.put("payment", item.get("payment"));
							childData .add(children);
						}
				}
			
				
				if(status.equals("WAIT_BUYER_PAY")){
					  WAIT_BUYER_PAY++;
				}else if(status.equals("WAIT_SELLER_SEND_GOODS")){
					WAIT_SELLER_SEND_GOODS++;
				}else if(status.equals("WAIT_BUYER_CONFIRM_GOODS")){
					WAIT_BUYER_CONFIRM_GOODS++;
				}else if(status.equals("TRADE_FINISHED")){
					TRADE_FINISHED++;
				}else if(status.equals("TRADE_CLOSED") || status.equals("TRADE_CLOSED_BY_TAOBAO")){
					TRADE_CLOSED++;
				}
			}
				Map<String, Object>  temp1 = new HashMap<String, Object>();
				temp1.put("tradeState", "等待买家付款");
				temp1.put("tradeNum",WAIT_BUYER_PAY);
				mainlist.add(temp1);
				Map<String, Object>  temp2 = new HashMap<String, Object>();
				temp2.put("tradeState", "等待卖家发货");
				temp2.put("tradeNum",WAIT_SELLER_SEND_GOODS);
				mainlist.add(temp2);
				Map<String, Object>  temp3 = new HashMap<String, Object>();
				temp3.put("tradeState", "等待买家确认收货");
				temp3.put("tradeNum",WAIT_BUYER_CONFIRM_GOODS);
				mainlist.add(temp3);
				Map<String, Object>  temp4 = new HashMap<String, Object>();
				temp4.put("tradeState", "交易成功");
				temp4.put("tradeNum",TRADE_FINISHED);
				mainlist.add(temp4);
				Map<String, Object>  temp5 = new HashMap<String, Object>();
				temp5.put("tradeState", "交易关闭");
				temp5.put("tradeNum",TRADE_CLOSED);
				mainlist.add(temp5);
		} catch (JSONException e) {
			e.printStackTrace();
		} 
		result.put("mainlist", mainlist);
		result.put("childlist", childData);
		return result;
	}
	
	
	// 生成签名返回
	private static String getSign(Map<String, String> signMap) {
		TreeMap<String, String> apiparamsMap = new TreeMap<String, String>();
		// 组装协议参数（必须按照key值的升序排列）。
		for (String key : signMap.keySet()) {
			apiparamsMap.put(key, signMap.get(key));
		}
		apiparamsMap.put("app_key", AuthorInfo.APP_KEY);
		apiparamsMap.put("session", AuthorInfo.getInstance().topSession);
		apiparamsMap.put("sign_method", "md5");
		apiparamsMap.put("timestamp", DateTimeUtil.getDateFormat(new Date()));
		apiparamsMap.put("v", "2.0");
		// 生成签名
		String sign = Utils.sign(apiparamsMap, AuthorInfo.APP_SERCET);
		return sign;
	}
	
	/**
	 * 查询单个商品的信息
	 * @author wanggj
	 */
	public static ItemForDetail    getProductInfo(String num_iid){
		 ItemForDetail item =new ItemForDetail();
		HttpEngine httpEngine = new HttpEngine();
		httpEngine.getHttpClient();
		String fields = "title,price,pic_url,num,freight_payer,desc,num_iid";
		String method = "taobao.item.get";
		String format = "json";
		List<NameValuePair> params = httpEngine.getTopSessionUrl(method,
				fields, format, false);
		Map<String, String> signParams = new HashMap<String, String>();
		signParams.put("fields", fields);
		signParams.put("format", format);
		signParams.put("method", method);
		signParams.put("num_iid", num_iid);
		String sign = getSign(signParams);
		// 组装协议参数sign
		params.add(new BasicNameValuePair("sign", sign));
		params.add(new BasicNameValuePair("num_iid", num_iid));
		String resultStr = httpEngine.doPost(AuthorInfo.TOP_URL, params);
		try {
			JSONObject jsonObject = new JSONObject(resultStr).getJSONObject("item_get_response").getJSONObject("item"); 
			item.setTitle(jsonObject.getString("title"));
			item.setPic_url(jsonObject.getString("pic_url"));
			item.setNum(jsonObject.getString("num"));
			item.setPrice(jsonObject.getString("price"));
			item.setDesc(jsonObject.getString("desc"));
			item.setNum_iid(jsonObject.getString("num_iid"));
			item.setFreight_payer(jsonObject.getString("freight_payer"));
		} catch (JSONException e) {
			e.printStackTrace();
		} 
		return  item;
	}
	
	/**
	 * 商品下架
	 * @author wanggj
	 */
	public static  void proudctDelisting(String num_iid){
		HttpEngine httpEngine = new HttpEngine();
		httpEngine.getHttpClient();
		String method = "taobao.item.update.delisting";
		String format = "json";
		List<NameValuePair> params = httpEngine.getTopSessionUrl(method,"", format, false);
		Map<String, String> signParams = new HashMap<String, String>();
		signParams.put("format", format);
		signParams.put("method", method);
		signParams.put("num_iid", num_iid);
		String sign = getSign(signParams);
		// 组装协议参数sign
		params.add(new BasicNameValuePair("sign", sign));
		params.add(new BasicNameValuePair("num_iid", num_iid));
		String resultStr = httpEngine.doPost(AuthorInfo.TOP_URL, params);
		try {
			JSONObject jsonObject = new JSONObject(resultStr).getJSONObject("item_update_delisting_response").getJSONObject("item"); 
			String result  = jsonObject.getString("num_iid");
		} catch (JSONException e) {
			e.printStackTrace();
		} 
	}

}
